package cn.edu.cdu.health.controller;

import cn.edu.cdu.health.entity.Medicine;
import cn.edu.cdu.health.service.MedicineService;
import cn.edu.cdu.health.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/medicine")
public class MedicineController {

    @Autowired
    private MedicineService medicineService;

    // 新增药品接口
    @PostMapping("/save")
    public R<String> saveMedicine(@RequestBody Medicine medicine) {
        boolean success = medicineService.saveMedicine(medicine);
        if (success) {
            return R.success("药品新增成功");
        } else {
            return R.error("药品新增失败");
        }
    }

    // 修改药品信息
    @PutMapping("/update")
    public R<String> updateMedicine(@RequestBody Medicine medicine) {
        if (medicine.getId() == null) {
            return R.error("药品ID不能为空");
        }
        boolean success = medicineService.updateById(medicine);
        if (success) {
            return R.success("药品修改成功");
        } else {
            return R.error("药品修改失败");
        }
    }

    // 删除药品
    @DeleteMapping("/delete/{id}")
    public R<String> deleteMedicine(@PathVariable Long id) {
        if (id == null) {
            return R.error("药品ID不能为空");
        }
        boolean success = medicineService.removeById(id);
        if (success) {
            return R.success("药品删除成功");
        } else {
            return R.error("药品删除失败");
        }
    }

    // 根据ID查询药品
    @GetMapping("/{id}")
    public R<Medicine> getMedicineById(@PathVariable Long id) {
        Medicine medicine = medicineService.getById(id);
        if (medicine == null) {
            return R.error("药品不存在");
        }
        return R.success(medicine);
    }

    // 获取所有药品列表
    @GetMapping("/list")
    public R<List<Medicine>> getMedicineList() {
        List<Medicine> list = medicineService.list();
        return R.success(list);
    }
}